##散点加折线图
import json
from utils.getDataFromMysql import *
import numpy as np
from array import array
import math
from pictureData.AttributeObject import *


def safe_convert_to_float(value):
    try:
        return float(value)
    except ValueError:
        return 0.0

from utils.expand import *
@timecost
def generateScatterLineChart(result_list:list):
    ## 提取所需年份
    year_list = []
    ##提取标题头
    title_list = []
    ##提取对象属性列表集合
    attribute_list = []
    json_result = {}
    if (len(result_list) != 0):
        for item in result_list:
            tmp = item.__dict__
            year_tmp = tmp.get('year')
            if (year_tmp is not None and (year_tmp not in year_list)):
                year_list.append(year_tmp)
            country_tmp = tmp.get('country')
            norm_tmp = tmp.get('norm')
            units_tmp = tmp.get('units')
            title_tmp = str(country_tmp) + '_' + str(norm_tmp) + '_' + str(units_tmp)
            title_list.append(title_tmp)
            data_tmp = tmp.get('data_value')

            units_norm_tmp = norm_tmp+'('+units_tmp+')'
            country_with_norm = country_tmp+"_"+norm_tmp
            attribute_tmp = AttributeNode(title_tmp,year_tmp,data_tmp,country_tmp,units_norm_tmp,country_with_norm)
            attribute_list.append(attribute_tmp)


    original_array = np.array(year_list)
    unique_year_list = np.unique(original_array).tolist()
    json_result["echartX"] = unique_year_list

    original_title_array = np.array(title_list)
    unique_title_list = np.unique(original_title_array).tolist()
    json_result["echartNav"] = unique_title_list

    ##定义表头属性
    columns = []
    year_dict = {'prop':'year','label':'年份'}
    columns.append(year_dict)
    unique_title = {obj.getTitleName() for obj in attribute_list}
    if(len(unique_title) !=0):
        for title_name_tmp in unique_title:
            tmp_dict = {'prop':title_name_tmp,'label':title_name_tmp}
            columns.append(tmp_dict)
    json_result["columns"] = columns

    ##构建表格对应的属性值
    tableData = []
    if(len(year_list)!=0):
        for year in year_list:
            tableData_sigle_dict = {}
            tableData_sigle_dict['year'] = year
            for column in columns:
                if(column['prop'] != "year"):
                    # 使用生成器表达式和内置的 next 函数查找符合条件的对象
                    result = next((obj for obj in attribute_list if
                                   obj.getYear() == year and obj.getTitleName() == column['prop']), None)
                    if(result is not None):
                        tableData_sigle_dict[column['prop']] = result.getData()
                    else:
                        tableData_sigle_dict[column['prop']] = ''
            tableData.append(tableData_sigle_dict)
    json_result['tableData'] = tableData



    ##构建散点+折线图表中Y轴数据
    echartY = []
    unique_unit_norm_list = {obj.getUnitsWithNorm() for obj in attribute_list}
    if(len(unique_unit_norm_list) != 0):
        for index,unit_with_norm_tmp  in enumerate(unique_unit_norm_list):
            data = [safe_convert_to_float(obj.getData()) for obj in attribute_list if obj.getUnitsWithNorm() == unit_with_norm_tmp]
            max_value = max(data)
            # 间隔单位向上取整
            data_not_zero = [obj for obj in data if obj != 0 ]

            if(len(data_not_zero) > 0):
                interval = math.ceil(max_value / data_not_zero.__len__())
            else:
                interval = 1
            dict_tmp = {}
            dict_tmp['name'] = unit_with_norm_tmp
            dict_tmp['type'] = 'value'
            dict_tmp['min'] = 0
            dict_tmp['max'] = max_value
            dict_tmp['interval'] = interval
            if(index %2 == 0):
                position = 'left'
            else:
                position = 'right'
            dict_tmp['position'] = position
            echartY.append(dict_tmp)
    json_result['echartY'] = echartY

    ##构建折线图数据
    echartDataAxis = []
    if (len(unique_unit_norm_list) != 0):
        for index, unit_with_norm_tmp in enumerate(unique_unit_norm_list):
            dict_tmp = {}
            if (index % 2 == 0):
                dict_tmp['type'] = 'line'
                dict_tmp['yAxisIndex'] = 0
            else:
                dict_tmp['type'] = 'scatter'
                dict_tmp['yAxisIndex'] = 1
            data_country_norm = [obj.getCounryWithNorm() for obj in attribute_list if obj.getUnitsWithNorm() == unit_with_norm_tmp]
            name_tmp = data_country_norm[0]
            dict_tmp['name'] = name_tmp
            data = [safe_convert_to_float(obj.getData()) for obj in attribute_list if obj.getUnitsWithNorm() == unit_with_norm_tmp]
            dict_tmp['data'] = data
            echartDataAxis.append(dict_tmp)
    json_result['echartDataAxis'] = echartDataAxis
    return json.dumps(json_result)



if __name__ == '__main__':
    sql_query = "select * from weo_data where country = 'Afghanistan' and norm in ('NGDP_R','NGDP_RPCH') "
    result_list = getDataBySql(sql_query)

    response = generateScatterLineChart(result_list)
    print(response)